package com.ftg.learn.util;

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @author kangjx
 * @createTime 2022/8/16
 */
@Configuration
public class SpringConfiguration {

    private final String url = "jdbc:mysql://localhost:3306/cool2204?serverTimezone=Asia/Shanghai";
    private final String username = "root";
    private final String password = "Love0913@kjx";
    private final String driverClass = "com.mysql.cj.jdbc.Driver";

    @Bean("sqlSessionFactory")
    @Primary
    public SqlSessionFactory initSqlSession() {
        org.apache.ibatis.session.Configuration conf = new org.apache.ibatis.session.Configuration();
        conf.setCacheEnabled(true);
        conf.setLazyLoadingEnabled(true);
        conf.setLogImpl(StdOutImpl.class);

        DataSource dataSource = new PooledDataSource(driverClass,url,username,password);
        TransactionFactory tf = new JdbcTransactionFactory();
        Environment e = new Environment("localMysql",tf,dataSource);
        conf.setEnvironment(e);
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(conf);


        return sqlSessionFactory;
    }

    @Bean
    public MapperScannerConfigurer initSqlSessionFactoryBean(){
        MapperScannerConfigurer msc = new MapperScannerConfigurer();
        msc.setBasePackage("com.ftg.learn.mapper");
        msc.setSqlSessionFactoryBeanName("sqlSessionFactory");
        return msc;
    }

}
